package longtd.app.game;

import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

public class Sprite {
	// Member variable
	private int x = 0;
	private int y = 0;
	private int width = 0;
	private int height = 0;
	int []DIRECTION_TO_ANIMATION_MAP = {3,1,0,2};
	
	private static int MAX_SPEED  = 5;
	private int xSpeed;
	private int ySpeed; 
	
	private int currentFrame = 0;	
	private static final int BMP_ROWS = 4;
	private static final int BMP_COLS = 3;
	private GameView gameView;
	private Bitmap mImageBmp;
	
	public Sprite(GameView view, Bitmap bmp){
		this.gameView = view;
		this.mImageBmp = bmp;
		this.width = mImageBmp.getWidth()/ BMP_COLS;
		this.height = mImageBmp.getHeight()/ BMP_ROWS;
		
		Random rnd = new Random();
		x = rnd.nextInt(gameView.getWidth() - width);
		y = rnd.nextInt(gameView.getHeight() - height);
		xSpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED;
		ySpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED;
	}
	
	/**
	 * Update position of Sprite 
	 */
	private void update(){
		if (x > gameView.getWidth() - width - xSpeed || x + xSpeed < 0){
			xSpeed = -xSpeed;
		}
		x = x + xSpeed;
		
		if (y > gameView.getHeight() - height - ySpeed || y + ySpeed < 0){
			ySpeed = -ySpeed;
		}
		y = y + ySpeed;		
		
		currentFrame = ++currentFrame % BMP_COLS;
	}
	
	
	public void onDraw(Canvas canvas){
		update();
		int srcX = currentFrame * width;
		int srcY = getAnimationRow() * height;
		Rect src = new Rect(srcX, srcY, srcX+ width, srcY + height);
		Rect dst = new Rect(x, y, x + width, y+ height);
		
		canvas.drawBitmap(mImageBmp, src , dst, null);
	}

	private int getAnimationRow() {
		// TODO Auto-generated method stub
		double dirDouble = (Math.atan2(xSpeed, ySpeed)	/ (Math.PI / 2) + 2);
		int direction = (int)Math.round(dirDouble) % BMP_ROWS;
		return DIRECTION_TO_ANIMATION_MAP[direction];
	}

	public boolean isCollition(float x2, float y2) {
		// TODO Auto-generated method stub
		return x2 > x && x2 < x+ width && y2 > y && y2 < y + height;
	}
	
}
